// pages/spray/analys.js
const app = getApp()
import * as echarts from '../../ec-canvas/echarts';
const utils = require('../../utils/util.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    skin: '',
    activeType: 'wendu',
    typeList: [{
      key: 1,
      type: 'wendu',
      name: '温湿度'
    }, {
      key: 2,
      type: 'qiti',
      name: '气体'
    }, {
      key: 3,
      type: 'thi',
      name: 'THI'
    }],

    list1: [], //温度湿度历史详情
    list2: [], //气体
    list3: [], //thi
    ec: {
      lazyLoad: true
    },
    timeList: [
      { key: 'day', value: '天' },
      { key: 'month', value: '月' },
      { key: 'year', value: '年' }
    ],
    tempBeginTime: '',
    tempEndTime: '',

    qitiBeginTime: '',
    qitiEndTime: '',

    thiBeginTime: '',
    thiEndTime: '',

    cishiChoose: 'day',
    areaId : '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.setNavBar()
    const { skin } = app.globalData
    this.setData({
      skin,
      areaId : options.areaId || 0,
      activeType : options.activeType || 'wendu'
    })
    this.getMockData(this.data.activeType)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  onChangeTab(e) {
    const {
      type
    } = e.currentTarget.dataset
    this.setData({
      activeType: type
    })
    this.getMockData(type)
  },

  toPageHistory() {
    wx.navigateTo({
      url: '/pages/spray/deviceLogHistory?areaId=' + this.data.areaId,
    })
  },
  toPageTempShiduHistory() {
    wx.navigateTo({
      url: '/pages/spray/tempDetaillist?areaId=' + this.data.areaId,
    })
  },
  toPageThiHistory () {
    wx.navigateTo({
      url: '/pages/spray/thiDetaillist?areaId=' + this.data.areaId,
    })
  },

  // 模拟数据
  getMockData(type) {
    switch(type) {
      case 'wendu':
        this.loadTempChart();
        break;
      case 'qiti':
        this.loadQitiChart();
        break;
      case 'thi':
        this.loadThiChart();
        break;
    }
    
  },
  loadTempChart : function() {
    let that = this;
    let threeDay = utils.getDay(-3), today = utils.getDay(0),
        params = {
          "areaId" : that.data.areaId,
          "beginTime" : that.data.tempBeginTime ? (that.data.tempBeginTime + " 00:00:00") : (threeDay + " 00:00:00"),
          "endTime" : that.data.tempEndTime ? (that.data.tempEndTime + " 23:59:59") : (today + " 23:59:59")
        };
    let top5 = [];
    utils.promiseGet('/wx/device/spray/getAreaTempData', params).then(function(res){
      let shiduSerialData = {
        name: '湿度',
        type: 'line',
        data: []
      }, wenduSerialData = {
        name : "温度",
        data: [],
        type: 'line',
        areaStyle: {}
      }
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var wenduArr = [],shiduArry = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var temp = new  Array(res.data.list[i].updateTime, res.data.list[i].temperature);
            wenduArr.push(temp);
            var wenduitem = new Array(res.data.list[i].updateTime, res.data.list[i].humidity);
            shiduArry.push(wenduitem);
            if (i < 5) {
              top5.push(res.data.list[i]);
            }
          }
          shiduSerialData.data = shiduArry;
          wenduSerialData.data = wenduArr;
        }
      }
      if (shiduSerialData.data.length == 0) {
        shiduSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (wenduSerialData.data.length == 0) {
        wenduSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }

      var series = new Array(shiduSerialData, wenduSerialData);
      console.log(series);
      that.initChartWendu({"series" : series});
      that.setData({
        'list1' : top5
      });
    }).catch(function(e){
      console.log(e);
    });
  },
  //---获取温度湿度图标参数 begin
  getTemperatureOption(temperatireOptions) {
    const option = {
      title: {
        left: 8,
        text: '温度/温度监控图',
        textStyle: {
          color: '#333333',
          fontSize: 14
        }
      },
      legend: {
        right: 24,
        data: ['温度', '湿度']
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          console.log(params);
          return (params[0].data[0] + '\n' +"湿度:" +  params[0].data[1] + "%")
            + '\n' +"温度:" +  params[1].data[1] + "℃";
        },
        axisPointer: {
          type: 'cross'
        },
        feature: {
          dataView: {show: true, readOnly: false},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      xAxis: {
        type: 'time',
        boundaryGap: false,
        axisTick: {
          show: false
        }
      },
      yAxis: [
        {
            type: 'value',
            name: '湿度(%)',
            min: 0,
            max: 100,
            position: 'right',
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#5470C6',
                    fontSize: 12
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
        },
        {
            type: 'value',
            name: '温度(°C)',
            min: 0,
            max: 100,
            position: 'left',
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#91CC75',
                    fontSize : 8
                }
            },
            axisLabel: {
                formatter: '{value}'
            }
        }
      ],
      series: temperatireOptions.series, 
      dataZoom: [
        {
          type: 'slider',
          show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
          start: 0,
          end: 100,
          // handleSize: 88  该属性是缩放手柄的宽度
        },
        {
          type: 'inside',
          start: 0,
          end: 100
        }
      ]
    };
    return option;
  }, //---获取温度湿度图标参数 end

  initChartWendu(data) {
    this.chartCmpWendu = this.selectComponent('#chart-wendu')
    this.chartCmpWendu.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      })
      chart.setOption(this.getTemperatureOption(data))
      return chart
    })
  },

  //获取气体的图标参数 begin
  getQasOptions(dataParams) {
    const option = {
      title: {
        left: 8,
        text: '气体监控图',
        textStyle: {
          color: '#333333',
          fontSize: 14
        }
      },
      legend: {
        right: 15,
        data: ['O2', 'H2S', 'NH3', '\n', 'ETO', 'CO2'],
        textStyle: {
          fontSize: 10
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          console.log(params);
          return (params[0].data[0] + '\n' +"O2:" +  params[0].data[1])
             + '  ' +"H2S:" +  params[1].data[1]
             + '\n' +"NH3:" +  params[2].data[1]
             + '  ' +"eto:" +  params[3].data[1]
             + '\n' +"co2:" +  params[4].data[1];
        },
        axisPointer: {
          type: 'cross'
        },
        feature: {
          dataView: {show: true, readOnly: false},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      xAxis: {
        type: 'time',
        boundaryGap: false,
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        name: '气体(ppm)',
        position: 'left',
        axisLine: {
            show: true,
            lineStyle: {
                color: '#5470C6',
                fontSize: 12
            }
        },
        axisLabel: {
            formatter: '{value}'
        }
      },
      series: dataParams.series, 
      dataZoom: [
        {
          type: 'slider',
          show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
          start: 0,
          end: 100,
          // handleSize: 88  该属性是缩放手柄的宽度
        },
        {
          type: 'inside',
          start: 0,
          end: 100
        }
      ]
    };
    return option;
  }, //获取气体的图标参数 emd
  loadQitiChart : function() {
    let that = this;
    let threeDay = utils.getDay(-3), today = utils.getDay(0),
        params = {
          "areaId" : that.data.areaId,
          "beginTime" : that.data.qitiBeginTime ? (that.data.qitiBeginTime + " 00:00:00") : (threeDay + " 00:00:00"),
          "endTime" : that.data.qitiEndTime ? (that.data.qitiEndTime + " 23:59:59") : (today + " 23:59:59")
        };
    let top5 = [];
    utils.promiseGet('/wx/device/spray/getAreaTempData', params).then(function(res){
      let o2SerialData = {
        name: 'O2',
        type: 'line',
        data: [],
        lineStyle : {
          color : '#D15FEE'
        }
      }, h2sSerialData = {
        name : "H2S",
        data: [],
        type: 'line',
        lineStyle : {
          color : '#EEE685'
        }
      },nhthreeSerialData = {
        name : "NH3",
        data: [],
        type: 'line',
        lineStyle : {
          color : '#4876FF'
        }
      },etoSerialData = {
        name : "ETO",
        data: [],
        type: 'line',
        lineStyle : {
          color : '#98FB98'
        }
      },co2SerialData = {
        name : "CO2",
        data: [],
        type: 'line',
        areaStyle: {},
        lineStyle : {
          color : '#A0522D'
        }
      };
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var o2Arr = [],h2sArry = [],nhthreeArr = [],etoArray = [],co2Array = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var temp = new  Array(res.data.list[i].updateTime, res.data.list[i].otwo);
            o2Arr.push(temp);
            var h2sitem = new Array(res.data.list[i].updateTime, res.data.list[i].htwos);
            h2sArry.push(h2sitem);
            var nhthreeitem = new Array(res.data.list[i].updateTime, res.data.list[i].nhthree);
            nhthreeArr.push(nhthreeitem);
            var etoitem = new Array(res.data.list[i].updateTime, res.data.list[i].eto);
            etoArray.push(etoitem);
            var cotwoitem = new Array(res.data.list[i].updateTime, res.data.list[i].cotwo);
            co2Array.push(cotwoitem);
          
            let gasItem = {
              'id' : res.data.list[i].psdId,
              'time' : res.data.list[i].updateTime,
              'list' : [
                {"id" : 1, "value" : "NNH3(0.1ppm)--" + res.data.list[i].nhthree	},
                {"id" : 2, "value" : "H2S(0.1ppm)--" + res.data.list[i].htwos	},
                {"id" : 3, "value" : "O2(0.1%ppmL)--" + res.data.list[i].otwo	},
                {"id" : 4, "value" : "eto(0.1ppm)--" + res.data.list[i].eto	},
                {"id" : 4, "value" : "cotwo(0.1ppm)--" + res.data.list[i].cotwo	},
              ]
            };
            if (i < 5) {
              top5.push(gasItem);
            }
          }
          o2SerialData.data = o2Arr;
          h2sSerialData.data = h2sArry;
          nhthreeSerialData.data = nhthreeArr;
          etoSerialData.data = etoArray;
          co2SerialData.data = co2Array;
        }
      }
      if (o2SerialData.data.length == 0) {
        o2SerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (h2sSerialData.data.length == 0) {
        h2sSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (nhthreeSerialData.data.length == 0) {
        nhthreeSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (etoSerialData.data.length == 0) {
        etoSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }
      if (co2SerialData.data.length == 0) {
        co2SerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }

      var series = new Array(o2SerialData, h2sSerialData, nhthreeSerialData, etoSerialData, co2SerialData);
      console.log(series);
      that.initChartQiti({"series" : series});
      that.setData({'list2' : top5});
    }).catch(function(e){
      console.log(e);
    });
  },
  initChartQiti(data) {
    this.chartCmpQiti = this.selectComponent('#chart-qiti')
    this.chartCmpQiti.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      })
      chart.setOption(this.getQasOptions(data))
      return chart
    })
  },

  //获取thi的图标参数
  getThiOptions(dataParams) {
    const option = {
      title: {
        left: 8,
        text: 'Thi监控图',
        textStyle: {
          color: '#333333',
          fontSize: 14
        }
      },
      legend: {
        right: 24,
        data: ['Thi']
      },
      tooltip: {
        trigger: 'axis',
        formatter: function(params) {
          console.log(params);
          return (params[0].data[0] + '\n' +"Thi:" +  params[0].data[1]);
        },
        axisPointer: {
          type: 'cross'
        },
        feature: {
          dataView: {show: true, readOnly: false},
          restore: {show: true},
          saveAsImage: {show: true}
        }
      },
      xAxis: {
        type: 'time',
        boundaryGap: false,
        axisTick: {
          show: false
        }
      },
      yAxis: {
        type: 'value',
        name: 'Thi(%)',
        position: 'left',
        axisLine: {
            show: true,
            lineStyle: {
                color: '#5470C6',
                fontSize: 12
            }
        },
        axisLabel: {
            formatter: '{value}'
        }
      },
      series: dataParams.series, 
      dataZoom: [
        {
          type: 'slider',
          show: false,//show属性为false不展示缩放手柄，为true展示缩放手柄
          start: 0,
          end: 100,
          // handleSize: 88  该属性是缩放手柄的宽度
        },
        {
          type: 'inside',
          start: 0,
          end: 100
        }
      ]
    };
    return option;
  }, //获取Thi的图标参数 emd
  loadThiChart : function() {
    let that = this;
    let threeDay = utils.getDay(-3), today = utils.getDay(0),
        params = {
          "areaId" : that.data.areaId,
          "beginTime" : that.data.thiBeginTime ? (that.data.thiBeginTime + " 00:00:00") : (threeDay + " 00:00:00"),
          "endTime" : that.data.thiEndTime ? (that.data.thiEndTime + " 23:59:59") : (today + " 23:59:59")
        };
    let top5 = [];
    utils.promiseGet('/wx/device/spray/getAreaTempData', params).then(function(res){
      let thiSerialData = {
        name: 'Thi',
        type: 'line',
        data: []
      };
      if (res.code == 200 && res.data) {
        if (res.data.list.length > 0) {
          var thiArr = [];
          for (var i = 0; i < res.data.list.length; i++) {
            var temp = new  Array(res.data.list[i].updateTime, res.data.list[i].thi);
            thiArr.push(temp);
            if (i < 5) {
              top5.push(res.data.list[i]);
            }
          }
          thiSerialData.data = thiArr;
        }
      }
      if (thiSerialData.data.length == 0) {
        thiSerialData.data = new Array(new Array(utils.formatTime(new Date()), 0));
      }

      var series = new Array(thiSerialData);
      console.log(series);
      that.initChartThi({"series" : series});
      that.setData({
        'list3' : top5
      });
    }).catch(function(e){
      console.log(e);
    });
  },
  initChartThi(data) {
    this.chartCmpThi = this.selectComponent('#chart-thi')
    this.chartCmpThi.init((canvas, width, height, dpr) => {
      const chart = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr
      })
      chart.setOption(this.getThiOptions(data))
      return chart
    })
  },

  handleWenduBeginTimeChange(e) {
    this.setData({
      tempBeginTime: e.detail
    })
    this.handleWenduTimeChange()
  },
  handleWenduEndTimeChange(e) {
    this.setData({
      tempEndTime: e.detail
    })
    this.handleWenduTimeChange()
  },
  handleWenduTimeChange() {
    const { tempBeginTime, tempEndTime } = this.data
    if (tempBeginTime && tempEndTime) {
      this.loadTempChart();
    }
  },

  handleQitiBeginTimeChange(e) {
    this.setData({
      qitiBeginTime: e.detail
    })
    this.handleQitiTimeChange()
  },
  handleQitiEndTimeChange(e) {
    this.setData({
      qitiEndTime: e.detail
    })
    this.handleQitiTimeChange()
  },
  handleQitiTimeChange() {
    const { qitiBeginTime, qitiEndTime } = this.data
    if (qitiBeginTime && qitiEndTime) {
      this.loadQitiChart();
    }
  },

  handleThiBeginTimeChange(e) {
    this.setData({
      thiBeginTime: e.detail
    })
    this.handleThiTimeChange()
  },
  handleThiEndTimeChange(e) {
    this.setData({
      thiEndTime: e.detail
    })
    this.handleThiTimeChange()
  },
  handleThiTimeChange() {
    const { thiBeginTime, thiEndTime } = this.data
    if (thiBeginTime && thiEndTime) {
      this.loadThiChart();
    }
  },

  
  handleCishuChange(e) {
    this.setData({ cishiChoose: e.detail })
  },
})